package com.cash.app.ui.login

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.cash.app.base.BaseViewModel
import com.cash.app.manager.GlobalTaskManager
import com.cash.app.manager.LoginManager
import com.cash.app.net.NetRequestExecutor
import com.cash.app.net.RetrofitClient
import com.cash.app.ui.login.api.LoginAPIService
import com.cash.app.ui.login.model.GetCodeRequest
import com.cash.app.ui.login.model.LoginRequest
import com.cash.app.utils.TLog

class LoginViewModel : BaseViewModel() {

    private val TAG = "LoginViewModel"

    private val loginApiService = RetrofitClient.createService(LoginAPIService::class.java)

    private val _loginResult = MutableLiveData<Boolean>()
    val loginResult: LiveData<Boolean> = _loginResult

    private val _getCodeResult = MutableLiveData<Boolean>()
    val getCodeResult: LiveData<Boolean> = _getCodeResult

    // Function to handle login
    fun login(phone: String, code: String) {
        launchRequest(request = {
            NetRequestExecutor.baseNetRequest {
                loginApiService.login(LoginRequest(phone, code))
            }
        }, onSuccess = { response ->
            response?.let {
                TLog.d("login info=$response", TAG)
                LoginManager.updateLoginState(response)
                GlobalTaskManager.startTasksAfterLogin()
            }
            _loginResult.value = true
        }, onError = { _, _ ->
            _loginResult.value = false
        })
    }

    // Function to get verification code
    fun getCode(mobileNumber: String, isChannel: Int = 0) {
        launchRequest(request = {
            NetRequestExecutor.baseNetRequest {
                loginApiService.getCode(GetCodeRequest(mobileNumber, isChannel))
            }
        }, onSuccess = {
            _getCodeResult.value = true
        }, onError = { _, _ ->
            _getCodeResult.value = false
        })
    }
} 